package com.yy.xshell.handle;

import com.alibaba.fastjson2.JSONObject;
import com.yy.xshell.EventType;
import com.yy.xshell.SshMsgDtO;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author wxy
 * @version 1.0
 * @date 2024/8/5 16:41
 */
public class WebSocketServerHandle extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private Logger log = LoggerFactory.getLogger(WebSocketServerHandle.class);



    protected void messageReceived(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();
        if(StringUtils.isEmpty(text)){
            return;
        }
        SshMsgDtO sshMsg = JSONObject.parseObject(text, SshMsgDtO.class);
        log.info("接收到数据：{}", text);
        System.out.println("接收到数据：" + text);
        Channel channel = channelHandlerContext.channel();
        sshMsg.setChannel(channel);
        sshMsg.setUserId(channel.id().asLongText());
        EventType eventType = EventType.getByType(sshMsg.getType());
        eventType.invoke(sshMsg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        log.warn("链接事件");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        log.warn("断开链接事件");
        SshMsgDtO sshMsgDtO = new SshMsgDtO();
        sshMsgDtO.setUserId(ctx.channel().id().asLongText());
        EventType.BREAK_ALL_CHANNEL.invoke(sshMsgDtO);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        log.warn("异常事件");
    }
}
